﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Serilog;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using WebCoreAdmin.Common;
using WebCoreAdmin.Controllers;
using WebCoreAdmin.Middlewares;
using WebCoreAdmin.Models;

namespace WebCoreAdmin
{
    public class Startup
    {
        public readonly OrmLiteConnectionFactory fac = new OrmLiteConnectionFactory($"{AppDomain.CurrentDomain.BaseDirectory}config.db", SqliteOrmLiteDialectProvider.Instance);
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            using (var db = fac.OpenDbConnection())
            {
                db.CreateTableIfNotExists<CategoryViewModel>();
                db.CreateTableIfNotExists<UploadfileViewModel>();
            }

//            services.Configure<CookiePolicyOptions>(options =>
//            {
//                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
//                options.CheckConsentNeeded = context => true;
//                options.MinimumSameSitePolicy = SameSiteMode.None;
//            });
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
                {
                    o.AccessDeniedPath = new PathString("/Account/Login");
                    o.LoginPath = new PathString("/Account/Login");
                    //超时退出
                    o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
                });




            services.AddMvc()
                .AddJsonOptions(opt =>
                {
                    opt.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                    opt.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
                    opt.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    //使用Newtonsoft.Json进行序列化
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton(fac);
            var publicKey =
                @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsm9r+noXyrrJ2XIMiNckXna+y6yg/uA9sEmKP2ub4TGFdIkRgiLYRMGo2+D5Iu8byYwZZIzqVlU43RDeLBLXKdb92zdqEouhnHXw5jJ482G4gJTKMI0yAq8HDv3C8i2sk4ZvmJChVs7m5Frpik+6PdUagEwhgtot14f/e1lXBtAG8Pn5WLG9+SaM0z/UFmH3hRjt85VObXVG3BHZ+DBnzKQD3i7FxeblzK2mpASO0cW0wEqym4xUYGQ+yCeoJwnv1s7YqBtJqB15ztQsYMTD5UxNk3fKXw8rgId2qpi+EU15vwXTpBCQ0l1iRS8vI2Z1Y392WIe/Kilwrjkq5YougwIDAQAB";
            var privateKey =
                @"MIIEpAIBAAKCAQEAsm9r+noXyrrJ2XIMiNckXna+y6yg/uA9sEmKP2ub4TGFdIkRgiLYRMGo2+D5Iu8byYwZZIzqVlU43RDeLBLXKdb92zdqEouhnHXw5jJ482G4gJTKMI0yAq8HDv3C8i2sk4ZvmJChVs7m5Frpik+6PdUagEwhgtot14f/e1lXBtAG8Pn5WLG9+SaM0z/UFmH3hRjt85VObXVG3BHZ+DBnzKQD3i7FxeblzK2mpASO0cW0wEqym4xUYGQ+yCeoJwnv1s7YqBtJqB15ztQsYMTD5UxNk3fKXw8rgId2qpi+EU15vwXTpBCQ0l1iRS8vI2Z1Y392WIe/Kilwrjkq5YougwIDAQABAoIBAEd6ZOngsNkwPB2UFztV26bPsJyMWa3gDDYrL2s6YyYxnUFSiyXzaWkZntf95i89U4dITP+/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RwLvCowOndc60Z4SRV7XCeYTqdAZDqauq3AkBlyWuDAu1+xK7lU9OULyEaqRBeNpjRoQ==";
            RsaHelper rsaHelper=new RsaHelper(RsaHelper.RsaType.Rsa2,Encoding.UTF8, privateKey,publicKey);
            services.AddSingleton(MD5.Create());
            services.AddSingleton(rsaHelper);
            services.AddMemoryCache();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        {
            var serilog = new LoggerConfiguration()
                          .MinimumLevel.Debug()
                          .Enrich.FromLogContext()
                          .WriteTo.RollingFile("a.log",
                                               outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {Message}{NewLine}{Exception}");

            loggerFactory.AddSerilog(serilog.CreateLogger());
            applicationLifetime.ApplicationStarted.Register(() =>
                                                            {
                                                                Console.WriteLine("ApplicationStarted");
                                                            });
            applicationLifetime.ApplicationStopped.Register(() =>
                                                            {
                                                                Console.WriteLine("ApplicationStopped");
                                                            });
            applicationLifetime.ApplicationStopping.Register(() =>
                                                             {
                                                                 Console.WriteLine("ApplicationStopping");
                                                                 applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush);
                                                             });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

//            AppUseRewriterHttps(app);
            
            app.UseStaticFiles();
            app.UseMiddleware<ResponseTimeMiddleware>();
            app.UseAuthentication();
//            app.UseClientCertMiddleware();

//            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        /// <summary>
        /// https重定向
        /// </summary>
        /// <param name="app"></param>
        public void AppUseRewriterHttps(IApplicationBuilder app)
        {
            var options = new RewriteOptions()
            .AddRedirectToHttps(StatusCodes.Status301MovedPermanently, 443);
            app.UseRewriter(options);
        }

    }
}
